<?php
namespace app\api\controller;

use app\common\service\WechatPayService;
use think\facade\Request;

class Pay
{
    /**
     * JSAPI支付下单
     */
    public function jsapi()
    {
        $openid = Request::param('openid');
        $orderNo = Request::param('order_no');
        $amount = Request::param('amount');
        $description = Request::param('description', '商品描述');

        try {
            $service = new WechatPayService();
            $result = $service->jsapiPay($openid, $orderNo, $amount, $description);

            // 获取前端支付参数
            $jsApiParams = $service->getJsApiParams($result['prepay_id']);

            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => $jsApiParams
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg'  => $e->getMessage()
            ]);
        }
    }

    /**
     * 小程序支付下单
     */
    public function mini()
    {
        $openid = Request::param('openid');
        $orderNo = Request::param('order_no');
        $amount = Request::param('amount');
        $description = Request::param('description', '商品描述');

        try {
            $service = new WechatPayService();
            $result = $service->miniPay($openid, $orderNo, $amount, $description);

            // 小程序支付参数与JSAPI相同
            $jsApiParams = $service->getJsApiParams($result['prepay_id']);

            return json([
                'code' => 1,
                'msg'  => 'success',
                'data' => $jsApiParams
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg'  => $e->getMessage()
            ]);
        }
    }

    /**
     * 支付通知回调
     */
    public function notify()
    {
        $service = new WechatPayService();
        $inBody = file_get_contents('php://input');
        $headers = getallheaders();

        try {
            // 验证签名
            $inWechatpaySignature = $headers['Wechatpay-Signature'] ?? '';
            $inWechatpayTimestamp = $headers['Wechatpay-Timestamp'] ?? '';
            $inWechatpaySerial = $headers['Wechatpay-Serial'] ?? '';
            $inWechatpayNonce = $headers['Wechatpay-Nonce'] ?? '';

            // 这里需要实现签名验证逻辑
            // ...

            $data = json_decode($inBody, true);
            $outTradeNo = $data['out_trade_no'];
            $transactionId = $data['transaction_id'];

            // 处理订单逻辑
            // ...

            // 返回成功响应
            return json([
                'code' => 'SUCCESS',
                'message' => '成功'
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            // ...

            return json([
                'code' => 'FAIL',
                'message' => $e->getMessage()
            ]);
        }
    }
}